package com.ly.hotel.spainterface.nm;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.spainterface.nm.bean.NmXFActionBean;
import com.ly.hotel.spainterface.nm.bean.NmXFBuyItemBean;
import com.ly.hotel.spainterface.nm.bean.NmXFItemBean;
import com.ly.hotel.spainterface.nm.event.XFActionEvent;
import com.ly.hotel.spainterface.nm.event.XFBuyResEvent;
import com.ly.hotel.spainterface.nm.event.XFUpdateCartEvent;
import com.ly.hotel.util.ImageUtil;
import com.ly.hotel.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;


/**
 * Created by SHUBEN on 2018/1/26.
 */

public class XFItemDetailsDialog extends Dialog {
    private MyApplication app;
    private NmXiaoFeiActivity mcontext;
    private NmXFItemBean itembean;
    private ImageView detailImg;
    private TextView itemName;
    private TextView itemPrice;// 单价
    private TextView itemRemark;
    private ImageButton addBt;
    private TextView itemCount;
    private int rod;
    private int count;
    private String typeName;
    private final int BUY_NOW = 1;
    private final int ADD_CART = 2;
    private List<NmXFActionBean> actionList = new ArrayList<>();
    private Map<String,String> actionMap;
    private LinearLayout actionLinear;


    public XFItemDetailsDialog(NmXiaoFeiActivity context, int theme, NmXFItemBean b,int c,String n) {
        super(context, theme);
        mcontext = context;
        itembean = b;
        count = c;
        typeName = n;
        app = (MyApplication) mcontext.getApplicationContext();
        rod = mcontext.getResources().getDimensionPixelSize(R.dimen.px6);
        List<NmXFActionBean> aList =  itembean.getAction();
        actionList.clear();
        if(aList != null && aList.size() > 0) {
            actionList.addAll(aList);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nm_xf_details);
        actionMap = new HashMap<>();
        EventBus.getDefault().register(this);

        detailImg = findViewById(R.id.xf_detial_img);
        itemName = findViewById(R.id.xf_details_name);
        itemPrice = findViewById(R.id.xf_detials_price);
        itemRemark = findViewById(R.id.xf_details_remark);
        itemCount = findViewById(R.id.xf_item_count);
        actionLinear = findViewById(R.id.xf_action_linear);

        ImageButton subBt = findViewById(R.id.xf_btn_sub);
        addBt = findViewById(R.id.xf_btn_add);
        final Button buyBtn = findViewById(R.id.xf_buyNow);
        Button addCartBtn = findViewById(R.id.xf_btn_addCart);

        subBt.setOnClickListener(btOnclick);
        addBt.setOnClickListener(btOnclick);
        buyBtn.setOnClickListener(btOnclick);
        addCartBtn.setOnClickListener(btOnclick);

        buyBtn.setOnKeyListener(onKeyListener);
        addCartBtn.setOnKeyListener(onKeyListener);

        itemName.setText(itembean.getName());
        itemPrice.setText(itembean.getPrice() + " " + mcontext.getResources().getString(R.string.xf_rmb)
                + "/" + itembean.getUnit());
        itemRemark.setText(itembean.getTime());
        ImageUtil.displayImage_Round(mcontext, MyApplication.getHostResUrl() + "/upload/interface/consume/pic/"
                + itembean.getId() + ".jpg",detailImg,rod);
        if(actionList.size() > 0){
            Map<String, List<NmXFActionBean>> map = new HashMap<>();
            for (NmXFActionBean ab : actionList){
                // map是否包含此key，若已经包含则添加一个新的数字到对应value集合中
                String tp = ab.getType();
                if (map.containsKey(tp)){
                    map.get(tp).add(ab);
                }else{
                    // map不包含此key，则重新创建一个新集合，并把这个类添加进集合
                    // ，再把集合放到map中
                    List<NmXFActionBean> newList = new ArrayList<>();
                    newList.add(ab);
                    map.put(tp, newList);
                }
            }
            setActionView(map);
        }else {
            LinearLayout actionLayout = findViewById(R.id.action_layout);
            View view = findViewById(R.id.action_line);
            actionLayout.setVisibility(View.GONE);
            view.setVisibility(View.GONE);
        }

        itemPrice.post(new Runnable() {
            @Override
            public void run() {
                buyBtn.requestFocus();
                buyBtn.requestFocusFromTouch();
            }
        });
    }

    private View.OnClickListener btOnclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.xf_btn_sub:
                    if(Integer.parseInt(itemCount.getText().toString()) > 1){
                        itemCount.setText(Integer.parseInt(itemCount.getText().toString()) - 1 + "");
                    }
                    break;
                case R.id.xf_btn_add:
                    if(Integer.parseInt(itemCount.getText().toString()) < count){
                        itemCount.setText(Integer.parseInt(itemCount.getText().toString()) + 1 + "");
                    }else{
                        ToastUtil.showShortToast(mcontext, mcontext.getResources().getString(R.string.xf_nomorethan)
                                + " " + count + " " + typeName, 2000);
                    }
                    break;
                case R.id.xf_buyNow:
                    operationItem(BUY_NOW);
                    EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_XIAOFEI + "\t" +
                            MyApplication.interfaceVersion + "\t" + "下单"));
                    break;
                case R.id.xf_btn_addCart:
                    operationItem(ADD_CART);
                    EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_XIAOFEI + "\t" +
                            MyApplication.interfaceVersion + "\t" + "加入购物车"));
                    break;
            }
        }
    };

    //立即下单或加入购物车
    private void operationItem(int type){
        List<NmXFBuyItemBean> byList = new ArrayList<NmXFBuyItemBean>();
        NmXFBuyItemBean bBean = new NmXFBuyItemBean();
        bBean.setId(itembean.getId());
        bBean.setName(itembean.getName());
        bBean.setPrice(Double.parseDouble(itembean.getPrice()));
        bBean.setTime(itembean.getTime());
        bBean.setType(itembean.getType());
        bBean.setUnit(itembean.getUnit());
        bBean.setNum(Integer.parseInt(itemCount.getText().toString()));
        String action = "";
        for(String act : actionMap.values()){
            action += act + "/";
        }
        bBean.setAction(action);
        switch (type){
            case BUY_NOW:
                byList.add(bBean);
                XFBuyDialog buydialog = new XFBuyDialog(mcontext,R.style.introDialog,byList);
                buydialog.setCanceledOnTouchOutside(false);//设置点击Dialog外部任意区域关闭Dialog
                buydialog.show();
                break;
            case ADD_CART:
                if(mcontext.getCartCount(bBean.getType(),bBean.getNum()) <= count) {
                    List<NmXFBuyItemBean> mycartList = app.shopCartList;
                    boolean isInCart = false;
                    for (NmXFBuyItemBean mi : mycartList) {
                        //编码和做法相同才是同一商品
                        if (mi.getId().equals(bBean.getId()) && mi.getAction().equals(bBean.getAction())) {
                            mi.setNum(mi.getNum() + bBean.getNum());
                            isInCart = true;
                        }
                    }
                    if (!isInCart) {
                        app.shopCartList.add(bBean);
                    }
                    EventBus.getDefault().post(new XFUpdateCartEvent(true,true));
                    dismiss();
                }else{
                    ToastUtil.showShortToast(mcontext, mcontext.getResources().getString(R.string.xf_nomorethan)
                            + " " + count + " " + typeName, 2000);
                }
                break;
        }
    }

    private View.OnKeyListener onKeyListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_UP){
                if(addBt != null){
                    addBt.requestFocusFromTouch();
                    addBt.requestFocus();
                    return true;
                }
            }
            return false;
        }
    };

    @Override
    protected void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    //根据不同的做法类型归类显示
    private void setActionView(Map<String, List<NmXFActionBean>> map){
        for (List<NmXFActionBean> la: map.values()){
            View view = LayoutInflater.from(mcontext).inflate(R.layout.xf_action_list,null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
            view.setLayoutParams(layoutParams);
            ListView listV = view.findViewById(R.id.id_myList);
            final NmXFActionAdapter adapter = new NmXFActionAdapter(mcontext,la);
            listV.setAdapter(adapter);
            listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //获取选中的参数
                    adapter.setSelectPosition(position);
                    adapter.notifyDataSetChanged();
                }
            });
            actionLinear.addView(view);
        }
    }

    //选择做法时收到的信息
    public void onEventMainThread(XFActionEvent e){
        String key = e.getType();
        if (TextUtils.isEmpty(e.getName())) {
            if(actionMap.containsKey(key)){
                actionMap.remove(key);
            }
        }else{
            actionMap.put(key,e.getName());
        }
    }


    //收到下单返回,成功关闭窗口
    public void onEventMainThread(XFBuyResEvent e) {
        if (e.getTag()){
            dismiss();
        }
    }
}